<template>
  <div class="update-gender">
    <van-picker
      show-toolbar
      title="标题"
      :columns="columns"
      :default-index="value"
      @cancel="$emit('close')"
      @confirm="onConfirm"
      @change="onPickerChange"
    />
  </div>
</template>

<script>
import { updateUserprofile } from "@/api/user.js";
export default {
  name: "UpdateGender",
  props: {
    value: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      columns: ["男", "女"],
      localGender: this.value,
    };
  },
  methods: {
    async onConfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true, // 禁止背景点击
        duration: 0, //持续展示
      });
      try {
        const localGender = this.localGender;
        await updateUserprofile({
          gender: localGender,
        });
        // 更新视图
        this.$emit("input", localGender);
        // 关闭弹层
        this.$emit("close");
        // 提示成功
        this.$toast.success("更新成功");
      } catch (error) {
        this.$toast.fail("更新失败");
      }
    },
    onPickerChange(picker, value, index) {
      // value是选中项的文字值，index是索引
      // 因为后台要的是0,1这种数据，所以赋予的是index
      this.localGender = index;
    },
  },
};
</script>

<style scoped lang="less"></style>
